import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Frame',
    component: () => import('@/views/front/Frame.vue'),
    redirect: '/home',
    children: [
      { path: '/home', component: () => import('@/views/front/Home.vue') },
      { path: '/articleDetail/:id', component: () => import('@/views/front/ArticleDetail.vue') },
      { path: '/searchList', component: () => import('@/views/front/SearchList.vue') },
      { path: '/category/:id', component: () => import('@/views/front/Category.vue') },
      { path: '/tag', component: () => import('@/views/front/Tag.vue') },
    ]
  },
  {
    path: '/admin',
    name: 'adminHome',
    redirect: '/admin/home'
  },
  {
    path: '/login',
    name: 'login',
    meta: { title: '登录' },
    component: () => import('@/views/admin/Login.vue')
  },
  {
    path: '/admin/home',
    component: () => import('@/views/admin/Home.vue'),
    redirect: '/admin/articleList',
    children: [
      { path: '/admin/welcome', component: () => import('@/components/Welcome.vue') },
      { path: '/admin/article', meta: { title: '写文章' }, component: () => import('@/components/article/Article.vue') },
      { path: '/admin/article/:id', meta: { title: '编辑文章' },  component: () => import('@/components/article/Article.vue') },
      { path: '/admin/articleList', meta: { title: '文章列表' }, component: () => import('@/components/article/ArticleList.vue') },
      { path: '/admin/category', meta: { title: '分类' }, component: () => import('@/components/article/Category.vue') },
      { path: '/admin/tags', meta: { title: '标签' }, component: () => import('@/components/article/Tags.vue') },
      { path: '/admin/modifyPwd', meta: { title: '修改密码' }, component: () => import('@/components/setting/ModifyPwd.vue') },
    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守护
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 从哪里来
  // next 放行
  if (to.meta.title) {
    document.title = to.meta.title + '-个人博客'
  }
  const path = to.path
  console.log(path);
  console.log(/\/admin/.test(path));
  if (path === '/login' || !(/\/admin/.test(path))) return next()
  const tokenStr = window.sessionStorage.getItem('user')
  if (!tokenStr) return next('/login')
  next()
})

export default router
